package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 专家抽取Controller
 *
 * @author ruoyi
 * @date 2024-10-28
 */
@RestController
@RequestMapping("/system/expertselect")
public class SysExpertSelectController extends BaseController {
    @Autowired
    private ISysExpertSelectService sysExpertSelectService;

    @Autowired
    private ISysExpertCustomGroupExpertService sysExpertCustomGroupExpertService;

    @Autowired
    private ISysProjectExpertExtractService sysProjectExpertExtractService;

    @Autowired
    private ISysProjectExpertPriorService sysProjectExpertPriorService;

    @Autowired
    private ISysExpertService sysExpertService;

    /**
     * 查询专家抽取列表
     */
    @PreAuthorize("@ss.hasPermi('system:expertselect:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysExpertSelect sysExpertSelect) {
        startPage();
        List<SysExpertSelect> list = sysExpertSelectService.selectSysExpertSelectList(sysExpertSelect);
        return getDataTable(list);
    }

    /**
     * 导出专家抽取列表
     */
    @PreAuthorize("@ss.hasPermi('system:expertselect:export')")
    @Log(title = "专家抽取", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysExpertSelect sysExpertSelect) {
        List<SysExpertSelect> list = sysExpertSelectService.selectSysExpertSelectList(sysExpertSelect);
        ExcelUtil<SysExpertSelect> util = new ExcelUtil<SysExpertSelect>(SysExpertSelect.class);
        util.exportExcel(response, list, "专家抽取数据");
    }

    /**
     * 获取专家抽取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:expertselect:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysExpertSelectService.selectSysExpertSelectById(id));
    }

    /**
     * 新增专家抽取
     */
    @PreAuthorize("@ss.hasPermi('system:expertselect:add')")
    @Log(title = "专家抽取", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysExpertSelect sysExpertSelect) {
        return toAjax(sysExpertSelectService.insertSysExpertSelect(sysExpertSelect));
    }

    /**
     * 修改专家抽取
     */
    @PreAuthorize("@ss.hasPermi('system:expertselect:edit')")
    @Log(title = "专家抽取", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysExpertSelect sysExpertSelect) {
        return toAjax(sysExpertSelectService.updateSysExpertSelect(sysExpertSelect));
    }

    /**
     * 删除专家抽取
     */
    @PreAuthorize("@ss.hasPermi('system:expertselect:remove')")
    @Log(title = "专家抽取", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysExpertSelectService.deleteSysExpertSelectByIds(ids));
    }

    @GetMapping("/expertextract/{expertselectid}")
    public AjaxResult doExpertExtract(@PathVariable Long expertselectid) {

        SysExpertSelect expertSelect = sysExpertSelectService.selectSysExpertSelectById(expertselectid);
        if (expertSelect == null) {
            return AjaxResult.error(HttpStatus.WARN, "专家抽取配置不存在");
        }

        if (expertSelect.getExtractedNum() == expertSelect.getProjectSectionQty()) {
            return AjaxResult.error(HttpStatus.WARN, "专家抽取已完毕");
        }

        /*
        int extractedExpertNum = expertSelect.getExtractedNum();        // 已经抽取专家人次
        List<String> noExpertIds = new ArrayList<String>();             // 回避专家
        if (expertSelect.getNoExpertId() != null) {
            noExpertIds = Arrays.asList(expertSelect.getNoExpertId().split(","));
        }*/

        SysExpert expertParams = new SysExpert();
        if (expertSelect.getAreaId() > 0){
            expertParams.setAreaId(Long.valueOf(expertSelect.getAreaId()));
        }
        // (0)area_id
        // (1)抽取专家类别
        if (expertSelect.getProjectExpertCategoryId() != null) {
            expertParams.setExpertCategoryIds(Arrays.asList(expertSelect.getProjectExpertCategoryId().split(",")));
        }
        // (2)回避专家
        if (expertSelect.getNoExpertId() != null) {
            expertParams.setNoExpertId(Arrays.asList(expertSelect.getNoExpertId().split(",")));
        }
        // (3)自定义专家组
        if (expertSelect.getExpertCustomGroupId() != null) {
            List<String> customGroupIds = new ArrayList<String>();             // 回避专家
            customGroupIds = Arrays.asList(expertSelect.getExpertCustomGroupId().split(","));
            SysExpertCustomGroupExpert expertCustomGroupExpert = new SysExpertCustomGroupExpert();
            expertCustomGroupExpert.setCustomGroupIds(customGroupIds);
            List<SysExpertCustomGroupExpert> customGroupExpertList = sysExpertCustomGroupExpertService.selectSysExpertCustomGroupExpertList(expertCustomGroupExpert);
            if (customGroupExpertList.size() > 0) {
                List<String> expertIds = new ArrayList<>();
                for (SysExpertCustomGroupExpert customGroupExpert : customGroupExpertList) {
                    expertIds.add(customGroupExpert.getExpertId());
                }
                expertParams.setExpertIds(expertIds);
            }
        }

        // 历史抽取结果
        int extractedNum = 0;   // 已抽取人数
        int number = 0;         // 已抽取次数
        SysProjectExpertExtract projectExpertExtractParams = new SysProjectExpertExtract();
        projectExpertExtractParams.setExpertSelectId(expertselectid);
        List<SysProjectExpertExtract> projectExpertExtractList = sysProjectExpertExtractService.selectSysProjectExpertExtractList(projectExpertExtractParams);
        if (projectExpertExtractList.size() > 0) {
            for (SysProjectExpertExtract projectExpertExtract : projectExpertExtractList) {
                // 设置已经抽取次数
                if (Integer.parseInt(projectExpertExtract.getNumber()) >= number) {
                    number = Integer.parseInt(projectExpertExtract.getNumber());
                }

                if (Integer.parseInt(projectExpertExtract.getStatus()) > 0) {
                    extractedNum = extractedNum + 1;
                }
            }

        }
        // 设置当前是第几次抽取
        number = number + 1;

        SysProjectExpertPrior projectExpertPriorParams = new SysProjectExpertPrior();
        projectExpertPriorParams.setExpertSelectId(expertselectid);
        projectExpertPriorParams.setNumber(Long.valueOf(number));
        List<SysProjectExpertPrior> projectExpertPriorList = sysProjectExpertPriorService.selectSysProjectExpertPriorList(projectExpertPriorParams);
        if (projectExpertPriorList.size() > 0) {
            List<String> expertIds = new ArrayList<>();
            if (expertParams.getExpertIds() != null) {
                expertIds = expertParams.getExpertIds();
            }
            for (SysProjectExpertPrior projectExpertPrior : projectExpertPriorList) {
                expertIds.add(projectExpertPrior.getExpertId().toString());
            }
            // 设置专家查询参数 expertParams
            expertParams.setExpertIds(expertIds);
        }

        // 查询符合条件的专家
        List<SysExpert> resultExpertList = sysExpertService.selectSysExpertList(expertParams);
        if (resultExpertList.size() == 0) {
            return AjaxResult.error(HttpStatus.WARN, "没有找到符合条件专家");
        }
        int nowExtractNum = expertSelect.getProjectSectionQty() - extractedNum;     // 当前改抽取人数
        if (nowExtractNum > resultExpertList.size()) {
            return AjaxResult.error(HttpStatus.WARN, "查询到的专家数量不足以本次专家抽取");
        }

        // 写入数据库
        for (int i = 0; i < nowExtractNum; i++) {
            SysProjectExpertExtract insetData = new SysProjectExpertExtract();
            insetData.setExpertSelectId(expertSelect.getId());
            insetData.setProjectId(expertSelect.getProjectId());
            insetData.setProjectName(expertSelect.getProjectName());
            insetData.setExpertId(resultExpertList.get(i).getId().toString());
            insetData.setExpertName(resultExpertList.get(i).getExpertName());
            insetData.setNumber(String.valueOf(number));
            insetData.setStatus("1");
            sysProjectExpertExtractService.insertSysProjectExpertExtract(insetData);
            extractedNum = extractedNum + 1;    // 设置已经抽取人数
        }
        expertSelect.setExtractedNum(extractedNum);
        expertSelect.setStatus(1);
        int result = sysExpertSelectService.updateSysExpertSelect(expertSelect);
        return toAjax(result);
    }
}
